﻿using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using STS.Model;
using System;


namespace STS.ViewModel
{
    public class LekViewModel : BaseViewModel
    {
        private ObservableCollection<Lek> _lekItems;
        public ObservableCollection<Lek> LekItems
        {
            get
            {
                if (_lekItems == null)
                {
                    _lekItems = new ObservableCollection<Lek>();
                }
                return _lekItems;
            }
            set
            {
                _lekItems = value;
                NotifyPropertyChanged("LekItems");
            }
        }

        public void FindLekItems()
        {
            var lekiDB = from Lek lek in ModelInstance.DataContext.LekItems
                         select lek;
            LekItems = new ObservableCollection<Lek>(lekiDB);
            Debug.WriteLine("Znalazłem leki, size = " + LekItems.Count);
        }

        public Lek FindLekById(int lekId)
        {
            var lekDB = from Lek lek in ModelInstance.DataContext.LekItems
                        where lek.Id == lekId
                        select lek;
            return lekDB.SingleOrDefault<Lek>();
        }

        public void UpdateLek(Lek updateLek)
        {
            Lek old = FindLekById(updateLek.Id);
            SetEntityPropertities(ref old, updateLek);
            SaveChangesToDB();
        }

        public void AddLek(Lek lek)
        {
            ModelInstance.DataContext.LekItems.InsertOnSubmit(lek);
            SaveChangesToDB();
            LekItems.Add(lek);
        }

        public void RemoveLek(Lek lek)
        {
            LekItems.Remove(lek);
            ModelInstance.DataContext.LekItems.DeleteOnSubmit(lek);
            SaveChangesToDB();
        }

        public void RemoveAllLeki()
        {
            var lekiDB = from Lek lek in ModelInstance.DataContext.LekItems
                         select lek;

            foreach (Lek _lek in lekiDB)
            {
                ModelInstance.DataContext.LekItems.DeleteOnSubmit(_lek);
            }

            try
            {
                SaveChangesToDB();
                LekItems.Clear();
            }
            catch (Exception e)
            {
                Debug.WriteLine(e);
            }
        }
    }
}
